package com.winit.openapi.es.controller;

import java.util.Date;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.es.manager.EsExceptionManager;
import com.winit.openapi.es.vo.SpanQuery;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.util.DateUtil;
import com.winit.openapi.util.ValidateUtil;

@Controller
@RequestMapping(value = "/winit/api/monitor")
public class APIMonitorController extends BaseController {

    private Logger             logger = LoggerFactory.getLogger(APIMonitorController.class);

    @Resource
    private EsExceptionManager esExceptionManager;

    @RequestMapping(value = "/exception/list")
    public String queryExceptionList(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {

        Object obj = requestMsg.getData();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;

            ValidateUtil.validNotNull(json, "startDate");
            ValidateUtil.validNotNull(json, "endDate");

            ValidateUtil.validDateString(json, "startDate", "yyyy-MM-dd HH:mm:ss");

            ValidateUtil.validDateString(json, "endDate", "yyyy-MM-dd HH:mm:ss");

            ValidateUtil.validDateBefore(json, "startDate", "endDate");

            // 最长不能超过一周：超过1周数据量大，会影响OPENAPI业务

            Date startDate = json.getDate("startDate");
            Date endDate = json.getDate("endDate");

            long interval = endDate.getTime() - startDate.getTime();
            int intervalDay = (int) (interval / (1000 * 60 * 60 * 24));

            if (intervalDay > 7) {
                throw new ApiException(ErrorCode.ES_SYN_DATE_INTERVAL_TOO_LONG_ERROR, "7");
            }

            SpanQuery query = new SpanQuery();
            query.setStartTimestamp(startDate.getTime());
            query.setEndTimestamp(endDate.getTime());

            logger.info("同步API监控平台异常信息：" + "startDate:" + DateUtil.parse2String(startDate, DateUtil.FULL_DATE_STRING)
                        + " endDate:" + DateUtil.parse2String(endDate, DateUtil.FULL_DATE_STRING));

            responseMsg.setData(esExceptionManager.queryExceptionList(query));

        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }

        return SUCCESS;
    }

}
